package com.worldcup.service.impl;

import com.worldcup.dao.CountryMapper;
import com.worldcup.dao.CountrySupportMapper;
import com.worldcup.model.Country;
import com.worldcup.model.CountrySupport;
import com.worldcup.service.CountryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author duwan.zq
 * @date 2018/05/31
 */
@Service
public class CountryServiceImpl implements CountryService {

    @Autowired
    private CountryMapper countryMapper;

    @Autowired
    private CountrySupportMapper countrySupportMapper;

    /** cache **/
    private final static Map<Integer, Country> COUNTRY_MAP = new HashMap<>(64);

    private final static Map<String, Country> COUNTRY_NAME_MAP = new HashMap<>(64);

    @PostConstruct
    public void init(){
        initCountryMap();
    }

    private void initCountryMap() {
        List<Country> countryList = this.listCountry(null);
        countryList.forEach(country -> COUNTRY_MAP.put(country.getId(), country));
    }

    public static Country getCountryCache(Integer countryId){
        return COUNTRY_MAP.get(countryId);
    }



    @Override
    public Country getCountry(Integer countryId) {
        return countryMapper.selectByPrimaryKey(countryId);
    }

    @Override
    public List<Country> getHotCountry(Integer limit) {
        return countryMapper.selectLimit(limit);
    }

    @Override
    public Country getCountry(String teamName) {
        Country country = COUNTRY_NAME_MAP.get(teamName);
        if(country == null){
            country =  countryMapper.selectByName(teamName);
            COUNTRY_NAME_MAP.put(teamName, country);
        }
        return country;
    }

    @Override
    public String getImageUrl(String awayTeam) {
        Country country = this.getCountry(awayTeam);
        return country == null ? null : country.getImgUrl();
    }

    @Override
    public List<Country> listCountry(String group) {
        return countryMapper.selectByGroupName(group);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Deprecated
    public void support(String openid, Integer countryId) {
        countryMapper.addSupportNum(countryId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void support(String openid, List<Integer> countryIds) {
        CountrySupport countrySupport = countrySupportMapper.selectLast(openid);
        if(countrySupport != null && isInToday(countrySupport.getCreatedAt())){
            throw new RuntimeException("今天已经投过票了！");
        }
        countryIds.forEach(id -> countryMapper.addSupportNum(id));
        countrySupport = new CountrySupport();
        countrySupport.setOpenid(openid);
        countrySupport.setCountryIds(StringUtils.join(countryIds, ','));
        countrySupportMapper.insert(countrySupport);

    }

    private boolean isInToday(long createdAt) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime begin = LocalDateTime.of(now.getYear(),now.getMonth(),now.getDayOfMonth(),0,0,0);
        now = now.plusDays(1L);
        LocalDateTime end = LocalDateTime.of(now.getYear(),now.getMonth(),now.getDayOfMonth(),0,0,0);
        return  createdAt >= begin.toEpochSecond(ZoneOffset.of("+8"))
            && createdAt < end.toEpochSecond(ZoneOffset.of("+8"));
    }
}
